from typing import List, Any
from pydantic import BaseModel
from fastapi import Request


class PageResult(BaseModel):
    total: int
    page: int
    items: List[Any]

# 自定义分页
async def paginate(queryset, request: Request, serializer=None):
    page_size = int(request.query_params.get('page_size', 10))
    page = int(request.query_params.get('page', 1))
    start = (page - 1) * page_size
    total = await queryset.count()
    items = await queryset.offset(start).limit(page_size).values() if serializer is None else await queryset.offset(start).limit(page_size).all()
    # 序列化查询结果
    if serializer is not None:
        items = [await serializer.from_tortoise_orm(item) for item in items]
    return PageResult(total=total, page=page, items=items)
